import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as path;

class RenamePagePlus extends StatefulWidget {
  @override
  _RenamePagePlusState createState() => _RenamePagePlusState();
}

class _RenamePagePlusState extends State<RenamePagePlus> {
  String _filePath = '';
  String _status = '';

  Future<void> _pickFile() async {
    final result = await FilePicker.platform.pickFiles();

    if (result == null) return;

    setState(() {
      _filePath = result.files.single.path!;
    });

    // Now you can use _filePath to rename the file
  }

  Future<void> _renameFile() async {
    final oldName = _filePath;

    // 分离文件路径的目录和文件名
    final directory = path.dirname(oldName);
    final fileName = path.basename(oldName);

    String fileNameWithoutExt = path.basenameWithoutExtension(fileName);

    String extension = path.extension(fileName);

    // 修改文件名，这里以添加"_renamed"为例
    final newFileName = "3$extension";

    // 重新组合目录和新的文件名
    final newName = path.join(directory, newFileName);

    try {
      final file = File(oldName);
      if (await file.exists()) {
        await file.rename(newName);
        setState(() {
          _status = 'File renamed successfully.';
        });
      } else {
        setState(() {
          _status = 'File does not exist.';
        });
      }
    } catch (e) {
      setState(() {
        _status = 'Error while renaming the file: $e';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('File Renaming Demo')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: _pickFile,
              child: Text('Pick File'),
            ),
            SizedBox(height: 16),
            Text('Selected File: $_filePath'),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: _renameFile,
              child: Text('Rename File'),
            ),
            SizedBox(height: 16),
            Text('Status: $_status'),
          ],
        ),
      ),
    );
  }
}
